package com.fileshare.web.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import lombok.*;
import org.springframework.util.CollectionUtils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class EmailUtil {
    private EmailUtil() {
    }

    //初始化参数
    private static Session initProperties(EmailParameter parameter) {
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", parameter.getProtocol());
        properties.setProperty("mail.smtp.host", parameter.getHost());
        // 端口
        String port = parameter.getPort();
        properties.setProperty("mail.smtp.port", port);
        // 使用smtp身份验证
        properties.put("mail.smtp.auth", "true");
        // 使用SSL,企业邮箱必需 start
        // 开启安全协议
        MailSSLSocketFactory mailSSLSocketFactory = null;
        try {
            mailSSLSocketFactory = new MailSSLSocketFactory();
            mailSSLSocketFactory.setTrustAllHosts(true);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        properties.put("mail.smtp.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        properties.put("mail.smtp.socketFactory.port", port);
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(parameter.getAccount(), parameter.getPassword());
            }
        });
        // 使用SSL,企业邮箱必需 end
        // TODO 显示debug信息 正式环境注释掉
        session.setDebug(parameter.getDebug());
        return session;
    }

    public static void send(EmailParameter parameter) {
        try {
            Session session = initProperties(parameter);
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(parameter.getAccount(), parameter.getSender()));// 发件人,可以设置发件人的别名
            // 收件人,多人接收
            InternetAddress[] internetAddressTo = InternetAddress.parse(parameter.getReceivers());
            mimeMessage.setRecipients(Message.RecipientType.TO, internetAddressTo);
            // 主题
            mimeMessage.setSubject(parameter.getSubject());
            // 时间
            mimeMessage.setSentDate(new Date());
            // 容器类 附件
            MimeMultipart mimeMultipart = new MimeMultipart();
            // 可以包装文本,图片,附件
            MimeBodyPart bodyPart = new MimeBodyPart();
            // 设置内容
            bodyPart.setContent(parameter.getContent(), "text/html; charset=UTF-8");
            mimeMultipart.addBodyPart(bodyPart);
            //添加附件
            if (!CollectionUtils.isEmpty(parameter.getAttaches())) {
                for (String attach : parameter.getAttaches()) {
                    bodyPart = new MimeBodyPart();
                    bodyPart.attachFile(attach);
                    mimeMultipart.addBodyPart(bodyPart);
                }
            }
            mimeMessage.setContent(mimeMultipart);
            mimeMessage.saveChanges();
            Transport.send(mimeMessage);
        } catch (MessagingException | IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        EmailParameter parameter = EmailParameter.builder()
                .account("")
                .password("")
                .debug(true)
                .content("")
                .attaches(null)
                .sender("")
                .receivers("")
                .subject("")
                .host("smtp.exmail.qq.com")
                .port("465")
                .protocol("smtp")
                .build();
        send(parameter);
    }

    @Getter
    @Setter
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class EmailParameter {
        private Boolean debug;
        private String account;
        private String password;
        private String sender;
        private String subject;
        private String content;
        private String receivers;
        private String port = "465";
        private String host = "smtp.exmail.qq.com";
        private String protocol = "smtp";
        private List<String> attaches;
    }
}
